<template>
  <iss-library-form-designer
    v-if="show"
    clearable
    generate-code
    generate-json
    preview
    import-json
    :custom-component-list="customComponentList"
  ></iss-library-form-designer>
  <!-- <renderer></renderer> -->
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import ElementUI from 'element-ui'
import renderer from '../components/personInfo_uQLoLPmF/renderer.vue'
export default {
  components:{renderer},
  data() {
    return {
      loading: false,
      customComponentList: [],
      componentInternalConfig: {
        name: '脚手架测试组件',
        icon: '',
        showDefaultValue: true,
        notFormItem: false,
        config: []
      },
      // 注入排除的依赖
      depMap: {
        vue: Vue,
        axios: axios,
        'element-ui': ElementUI
      }
    }
  },
  computed: {
    show() {
      return this.customComponentList.length > 0
    }
  },
  async created() {
    this.customComponentList = await this.getCustomComponentList()
  },
  methods: {
    parseUmdModule(jsText) {
      return new Promise((resolve, reject) => {
        let root = window
        root.define = function (...args) {
          // 自定义 define 方法，
          let func = null
          let depArr = []

          if (args.length > 1) {
            depArr = args[0]
            func = args[1]
          } else {
            func = args[0]
          }
          const deps = depArr.map(depName => {
            return this.depMap[depName]
          })
          const result = func(...deps) // 包依赖注入
          root.define = undefined // 移除伪装
          if (result) {
            resolve(result)
          } else {
            reject('解析组件错误')
          }
        }
        root.define.amd = true // 伪装成 amd 的 define。
        const scope = new Function(jsText)
        scope()
      })
    },
    loadCamp(url) {
      return new Promise((resolve, reject) => {
        axios
          .get(url, {
            cache: {
              maxAge: 24 * 60 * 1000
            },
            manual: true,
            overrideHeaders: true,
            headers: {
              'content-type': 'application/text'
            }
          })
          .then(res => {
            if (res.status === 200) {
              this.parseUmdModule(res.data).then(jsModule => {
                resolve(jsModule)
              })
            }
          })
      })
    },
    getCustomComponentList() {
      // 打包后的文件
      const files = require.context('../../public/dist/', false, /.js$/).keys()
      let list = []
      files.forEach(async item => {
        const code = item.split('.')[1].split('/')[1]
        const content =
          location.origin + location.pathname + '/dist/' + code + '.umd.min.js'
        let script = document.createElement('script')
        document.head.append(script)
        script.src = content
        this.loadCamp(content).then(module => {
          // 注册组件
          const componentNames = Object.keys(module).filter(
            item => item !== 'options_config' && item !== 'internal_config'
          )
          componentNames.forEach(name => {
            if(name.includes('Setter')) {
              Vue.component( name, module[name])
            }else{
              Vue.component(code + '-' + name, module[name])
            }
          })
          // 取配置文件里的配置
          let jsonSchema = module['options_config'].componentConfig
          if (jsonSchema && jsonSchema.options) {
            jsonSchema['customType'] = 'sourceCode'
            jsonSchema['disableFlag'] = false
          }
          // 组件名称
          this.componentInternalConfig.name = jsonSchema.name
          this.componentInternalConfig.config = module['internal_config']
          list.push({
            code,
            jsonSchema,
            content,
            componentInternalConfig: this.componentInternalConfig,
            collect: true,
            status: 'PUBLISHED'
          })
        })
      })
      return list
    }
  }
}
</script>
